package dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import common.RowMapper;
import common.SQLTemplate;

import pojo.Customer;
import pojo.Message;
import dao.MessageDAO;

public class MessageDAOImpl extends BaseDAO implements MessageDAO {

	@Override
	public Message getNewestMessage() {
		String sql = SQLTemplate.MESSAGE_SELECT_TEMPLATE + "LIMIT 0,1;";
		Message message = null;
		try {
			message = (Message) queryForObject(sql, new MessageRowMapper());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return message;
	}

	@Override
	public List<Message> getMessages() {
		String sql = SQLTemplate.MESSAGE_SELECT_TEMPLATE + ";";
		List<Message> messages = null;
		try {
			messages = (List<Message>) queryForList(sql, new MessageRowMapper());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return messages;
	}

	@Override
	public Message add(Message message) {
		String tableName = "T_MESSAGE";
		String[] columnNames = { "NOTICE" };
		String[] values = { message.getNotice() };
		String sql = SQLTemplate.addSQLTemplate(tableName, columnNames, values);
		try {
			insert(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return message;
	}

	@Override
	public Message update(Message message) {
		String tableName = "T_MESSAGE";
		String[] columnNames = { "NOTICE" };
		String[] values = { message.getNotice() };
		String sql = SQLTemplate.updateSQLTemplate(tableName, columnNames,
				values) + "WHERE ID='" + message.getId() + "';";
		;
		try {
			update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return message;
	}

	@Override
	public boolean deleteById(String id) {
		boolean state = false;
		String sql = SQLTemplate.deleteSQLTemplate("T_MESSAGE") + "WHERE ID='"
				+ id + "';";
		try {
			delete(sql);
			state = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return state;
	}

	private class MessageRowMapper implements RowMapper<Object> {
		private MessageRowMapper() {
		}

		public Message mapRow(ResultSet rs, int rowNum) throws SQLException {
			String id = rs.getString("id");
			String notice = rs.getString("notice");
			String time = rs.getString("time");
			Message message = new Message();
			if (id != null) {
				message.setId(id);
			}
			if (notice != null) {
				message.setNotice(notice);
			}
			if (time != null) {
				message.setTime(time);
			}
			return message;
		}
	}
}
